import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw,
  useRoute as useRouteX
} from 'vue-router'

import NProgress from '../utils/nprogress'

const routes: RouteRecordRaw[] = [
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('/@/views/Home/Home.vue'),
    meta: {
      title: '404not found'
    }
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('/@/views/Home/Home.vue'),
    meta: {
      title: '主页'
    }
  },
  {
    path: '/article/:articleId',
    name: 'Article',
    component: () => import('/@/views/Article/Article.vue'),
    meta: {
      title: '文章页'
    }
  },
  {
    path: '/editor',
    name: 'Editor',
    component: () => import('/@/views/Editor/Editor.vue'),
    meta: {
      title: '写文章',
      IsShowHead: false
    }
  },
  {
    path: '/editor/draft',
    name: 'ArticleDraft',
    component: () => import('/@/views/Article/ArticleDraft.vue'),
    meta: {
      title: '写文章',
    }
  },
  {
    path: '/editor/draft/:articleId',
    name: 'EditorDraft',
    component: () => import('/@/views/Editor/EditorDraft.vue'),
    meta: {
      title: '写文章',
      IsShowHead: false
    }
  },
  {
    path: '/user/:homeAddress',
    name: 'User',
    component: () => import('/@/views/User/UserHome.vue'),
    meta: {
      title: '个人主页'
    }
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('/@/views/Search/Search.vue'),
    meta: {
      title: '查询文章'
    }
  },
  {
    path: '/user/settings',
    name: 'UserSetting',
    component: () => import('/@/views/User/UserSetting.vue'),
    meta: {
      title: '个人资料'
    }
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
  strict: true,

  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由白名单
const whiteList = ['/', '/index', '/home', '/login', '/register']

router.beforeEach((to, from, next) => {
  NProgress.start()
  // if (whiteList.indexOf(to.path) === -1) {
  //   next({ path: '/' })
  // } else {
  //   next()
  // }

  document.title = to.meta.title as string
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router

export function useRoute() {
  return useRouteX()
}
